import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
import { dataTransFile, updateDataView, QuerySignCallback, sendBusinessMessage, JFsaveOrUpdate, houseApplyDelete, zhejiangVillageLoanInfolist } from '@/utils/api'
import timeFormat from '@/utils/timeFormat.js'
export default {
  install: async function (Vue, options) {
    Vue.prototype.getPdf = function (ele, pdfFileName) {
      var me=this;
      ele = document.getElementById('pdfDom')
      pdfFileName = pdfFileName || 'pdf'
      window.pageYoffset = 0 // 滚动置顶
      document.documentElement.scrollTop = 0
      document.body.scrollTop = 0
      // ele.style.fontSize = '18px'
      // ele.style.padding='30px';
      // let scale = window.devicePixelRatio * 2
      html2Canvas(ele, {
        // dpi: 300,
        dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
        scale: 4, // 按比例增加分辨率
        logging: false,
        // scale:scale,
        useCORS: true, // 允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
        allowTaint: false,
        height: ele.offsetHeight,
        width: ele.offsetWidth,
        windowWidth: document.body.scrollWidth,
        windowHeight: document.body.scrollHeight,
        backgroundColor: '#fff'
      }).then(async (canvas) => {
        // const _this = this
        // 未生成pdf的html页面高度
        var leftHeight = canvas.height
        var a4Width = 555.28 // 原A4宽 592 因为要设置边距 20 ,这里要减掉 40
        var a4Height = 801.89 // 原A4高   841 因为要设置边距 20 ,这里要减掉 40
        // 一页pdf显示html页面生成的canvas高度;
        var a4HeightRef = Math.floor((canvas.width / a4Width) * a4Height)

        // pdf页面偏移
        var position = 0

        var pageData = canvas.toDataURL('')
        var pdf = new JsPDF('x', 'pt', 'a4')
        // var index = 1
        const canvas1 = document.createElement('canvas')
        let height
        pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen')
        let me = this
        function createImpl(canvas) {
          if (leftHeight > 0) {
            // index ++
            var checkCount = 0
            if (leftHeight > a4HeightRef) {
              var i = position + a4HeightRef
              for (i = position + a4HeightRef; i >= position; i--) {
                var isWrite = true
                for (var j = 0; j < canvas.width; j++) {
                  var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data

                  if (c[0] !== 0xff || c[1] !== 0xff || c[2] !== 0xff) {
                    isWrite = false
                    break
                  }
                }
                if (isWrite) {
                  checkCount++
                  if (checkCount >= 10) {
                    break
                  }
                } else {
                  checkCount = 0
                }
              }
              height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef)
              if (height <= 0) {
                height = a4HeightRef
              }
            } else {
              height = leftHeight
            }

            canvas1.width = canvas.width
            canvas1.height = height
            var ctx = canvas1.getContext('2d')
            ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height) // 边距这里设置0，不然又黑边
            // var pageHeight = Math.round(a4Width / canvas.width * height)
            // pdf.setPageSize(null, pageHeight)
            if (position !== 0) {
              pdf.addPage()
            }
            // 设置 20px 边距
            pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 20, 20, a4Width, (a4Width / canvas1.width) * height)
            leftHeight -= height
            position += height
            if (leftHeight > 0) {
              // 添加全屏水印
              /* const base64 = ''
                            for (let i=0;i<6;i++) {
                              for (let j=0;j<5;j++) {
                                const  left = (j * 120) + 20
                                pdf.addImage(base64,'JPEG', left, i*150, 20, 30); // 关掉水印
                              }
                            } */
              setTimeout(createImpl, 0, canvas)
            } else {
              // pdf.save(pdfFileName + '.pdf')
            }
          }
        }
        debugger
        if (leftHeight > 0) {
          // var buffer = pdf.output("datauristring")
          // 将base64格式的字符串转换为file文件
          // var file = dataURLtoBlob(buffer)
          if (me.$store.state.toGuid.ROW_GUID) {
            var myfile = dataURLtoFile(pageData, pdfFileName)
            var formData1 = new FormData()
            let data = {
              toRowGuid: me.$store.state.toGuid.ROW_GUID,
              groupGuid: '2774cbb5-1854-4a0a-afaf-bee2e8f83cab'
            }
            formData1.append('file', myfile)
            formData.append('accessCode', '7a3fc061c866434b8475d3775c9ddcea')
            formData.append('cityCode', window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '')
            formData.append('paramStr', JSON.stringify(data))
            // 发起请求
            const res = await dataTransFile(formData1)

            if (JSON.parse(res.data.data).Success == true) {
              //调用更新状态
              if (!this.$store.state.isGJ) {
                var formData2 = [
                  {
                    PKID: me.$store.state.toGuid.PKID,
                    row_guid: me.$store.state.toGuid.ROW_GUID,
                    HTQDZT: '1',
                    HTGUID: JSON.parse(res.data.data).FileList[0].FILEGUID
                  }
                ]
              } else {
                var formData2 = [
                  {
                    PKID: me.$store.state.toGuid.PKID,
                    row_guid: me.$store.state.toGuid.ROW_GUID,
                    HTBHQDZT: '1',
                    HTGUID: JSON.parse(res.data.data).FileList[0].FILEGUID
                  }
                ]
              }
              let params = {
                accessCode: '77ad6c1591e54d4fbc45ecc90374a2a2',
                cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '',
                params: {
                  dataGuid: 'b68a5f59-7527-4cb8-bd8a-9b5451bb2d50',
                  strParams: JSON.stringify(formData2)
                }
              }
              const res1 = await QuerySignCallback(params)
              if (JSON.parse(res1.data.data).Success == true) {
                me.$toast({
                  type: 'success',
                  message: '提交成功！',
                  duration: 5000,
                  onClose: () => {
                    me.$router.push({
                      path: '/ZLJIndex'
                    })
                  }
                })
                // me.$toast.success("成功!");
                // // me.$notify({ type: 'success', message: '更新成功!' });
                // me.$router.push({
                //   path: "/ZLJIndex"
                // });
              }
            }
          }
        }
        // 当内容未超过pdf一页显示的范围，无需分页
        if (leftHeight < a4HeightRef) {
          pdf.addImage(pageData, 'JPEG', 20, 20, a4Width, (a4Width / canvas.width) * leftHeight)
          // var buffer = pdf.output("datauristring")
          // 将base64格式的字符串转换为file文件
          // var file = dataURLtoBlob(buffer)
          var myfile = dataURLtoFile(pageData, pdfFileName)
          var formData = new FormData()
          let data = {
            toRowGuid: this.$store.state.toGuid.row_guid,
            groupGuid: '188027de-4ba9-4218-bcb1-03bf764293fa'
          }
          formData.append('file', myfile)
          formData.append('accessCode', '7a3fc061c866434b8475d3775c9ddcea')
          formData.append('cityCode', window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '')
          formData.append('paramStr', JSON.stringify(data))
          // 发起请求
          var isNext = false
          if (pdfFileName == '委托书.png') {
            isNext = true
          } else {
            var params = this.$store.state.params
            let data1;
            if(params&&JSON.stringify(params)!='{}'){
              data1 = JSON.parse(params.params.strParams)[0]
            }
            //let data1 = JSON.parse(params.params.strParams)[0]
            if (!data1 || !data1.lsh) {
              this.$toast.fail('流水号为空,请重新申请')
              return
            }
            //调用gsa的保存接口
            let date1 = timeFormat(null, 'yyyy-mm-dd hh:MM:ss')
            console.log(data1, 'date')
            var paramss = {
              address: data1.address,
              applyphone: applyphone,
              applytime: date1, // yyyy-MM-dd HH:mm:ss
              cun: data1.CUN,
              dbrsfzh: '',
              dbrsjh: '',
              dbrxm: '',
              id: '',
              rowGuid: this.$store.state.toGuid.row_guid,
              idcard: data1.certificatecode,
              personname: data1.houseapplicant,
              s: data1.S,
              serialNumber: data1.lsh,
              town: data1.town,
              x: data1.X
            }
            if (data1.SQFS != 35) {
              paramss.dbrsfzh = data1.dbrsfzh
              paramss.dbrsjh = data1.dbrsjh
              paramss.dbrxm = data1.DBRXM
            }
            const res11 = await JFsaveOrUpdate(paramss)
            if (!res11.data.data) {
              this.$toast.fail('提交失败请稍后重试!')
              isNext = false
            } else {
              //存gsa的保存参数
              var cuncity = ''
              var applyphone = ''
              params.cityCode = window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000'
              if (JSON.parse(params.params.strParams)[0].SQFS == 35) {
                applyphone = JSON.parse(params.params.strParams)[0].applyphone
              } else {
                applyphone = JSON.parse(params.params.strParams)[0].dbrsjh
              }
              cuncity = JSON.parse(params.params.strParams)[0].CUN
              //先将申请中改为已申请
              const resresult = await QuerySignCallback(params)
              try {
                console.log(resresult)
                if (resresult.data.code == 500 || !JSON.parse(resresult.data.data).Success) {
                  this.$toast.fail('提交失败请稍后重试!')
                  let per = {
                    rowGuid: this.$store.state.toGuid.row_guid,
                    serialNumber: data1.lsh
                  }
                  const res11 = await houseApplyDelete(per)
                } else {
                  // 发送短信通知 两个存储过程查询
                  isNext = JSON.parse(resresult.data.data).Success == true || JSON.parse(resresult.data.data).Success == 'true' ? true : false
                }
              } catch (err) {
                this.$toast.fail('提交失败请稍后重试!')
                let per = {
                  rowGuid: this.$store.state.toGuid.row_guid,
                  serialNumber: data1.lsh
                }
                const res11 = await houseApplyDelete(per)
              }
            }
          }
          if (isNext) {
            try {
              var cuncitycode = cuncity
              let paerssendh = {
                procName: 'message',
                dtParams: JSON.stringify([{ I_USERID: cuncitycode, I_TYPE: 1 }])
              }
              let paramsendMEssageh = {
                accessCode: '69db6bece3a7480592e2ec753d1e335e',

                cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
                params: paerssendh
              }
              const reqwmsgh = await QuerySignCallback(paramsendMEssageh)
              const JSONSendh = JSON.parse(reqwmsgh.data.data)
              if (JSONSendh && JSONSendh.Data && JSONSendh.Data.length > 0) {
                //调用存储过程给农户和待办人人 如果是联建房 则在发脸见人
                let paerssendnh = {
                  procName: 'message2',
                  dtParams: JSON.stringify([
                    {
                      I_USERID: "'" + this.$store.state.toGuid.row_guid + "'",
                      I_TYPE: 1
                    }
                  ])
                }
                let paramsendMEssagenh = {
                  accessCode: '69db6bece3a7480592e2ec753d1e335e',

                  cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
                  params: paerssendnh
                }
                const reqwmsgnh = await QuerySignCallback(paramsendMEssagenh)
                const JSONreqwmsgnh = JSON.parse(reqwmsgnh.data.data)
                if (JSONreqwmsgnh && JSONreqwmsgnh.Data.length > 0) {
                  const JSONPhone = JSONreqwmsgnh.Data[0].PHONE.split(',')
                  JSONPhone.forEach((element) => {
                    let paramspersonss = {
                      mobiles: element,
                      templateId: '115c6adcfc014439bca8097c7a2bd8c2',
                      accessCode: '11b5cfe531954d94bb924c856e63a99b'
                    }
                    sendBusinessMessage(paramspersonss)
                  })
                }
              } else {
                let paerssendnh = {
                  procName: 'message2',
                  dtParams: JSON.stringify([
                    {
                      I_USERID: "'" + this.$store.state.toGuid.row_guid + "'",
                      I_TYPE: 1
                    }
                  ])
                }
                let paramsendMEssagenh = {
                  accessCode: '69db6bece3a7480592e2ec753d1e335e',
                  cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
                  params: paerssendnh
                }
                const reqwmsgnh = await QuerySignCallback(paramsendMEssagenh)
                const JSONreqwmsgnh = JSON.parse(reqwmsgnh.data.data)
                if (JSONreqwmsgnh && JSONreqwmsgnh.Data.length > 0) {
                  const JSONPhone = JSONreqwmsgnh.Data[0].PHONE.split(',')
                  JSONPhone.forEach((elements) => {
                    let paramsperson = {
                      mobiles: elements,
                      templateId: '8a5687a739394235b9b4f4ff6085b81a',
                      accessCode: '11b5cfe531954d94bb924c856e63a99b'
                    }
                    sendBusinessMessage(paramsperson)
                  })
                }
                //没有配置村委给农户发短信
              }
            } catch (e) {}
            const res = await dataTransFile(formData)
            if (pdfFileName == '委托书.png') {
              this.$router.push({
                path: '/qianMing',
                query: {
                  data1: this.$store.state.toGuid,
                  formData: this.$store.state.toGuid1
                }
              })
            } else {
              debugger
                //查询美丽乡居贷 是否有数据
               try{
                let param = {
                  cityCode: this.$store.state.toGuid.town,
                  pageNo: 1,
                  pageSize: 10
                }
                let result = await zhejiangVillageLoanInfolist(param)
                debugger
                if (result.data.data && result.data.data.pageList.length > 0) {
                  //弹出美丽乡居贷宣传图片
                  this.$router.push({
                    path: '/Submit'
                  })
                  
                 // window.localStorage.setItem('isLogin', true)
                }else{
                  this.$toast({
                    type: 'success',
                    message: '提交成功！',
                    duration: 5000,
                    onClose: () => {
                      this.$router.push({
                        path: '/ZLJIndex'
                      })
                    }
                  })
                }
               }catch(e){
                this.$toast({
                  type: 'success',
                  message: '提交成功！',
                  duration: 5000,
                  onClose: () => {
                    this.$router.push({
                      path: '/ZLJIndex'
                    })
                  }
                })
               }
            }
          } else {
            this.$toast.fail('提交失败请稍后重试')
          }
        } else {
          try {
            pdf.deletePage(0)
            setTimeout(createImpl, 0, canvas)
          } catch (err) {}
        }
      })
    }
  }
}

//将base64转换为文件对象
function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  //转换成file对象
  return new File([u8arr], filename, { type: mime })
  //转换成成blob对象
  //return new Blob([u8arr],{type:mime});
}
